package com.dingshi.security;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.UpdateApi;
import com.dingshi.security.api.WeatherApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.entity.VersionInfo;
import com.dingshi.security.util.StringUtils;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.MainClockView;
import com.dingshi.security.view.MainTitleView;
import com.dingshi.security.view.UpdateDialog;

public class HomeActivity extends BaseActivity implements OnClickListener {
	public static final String USER_TYPE_REPAIR = "1";
	public static final String USER_TYPE_SERVICE = "2";
	private ImageButton btn_dial;
	private ImageButton btn_notify;
	private ImageButton btn_center;
	private ImageButton btn_clock_or_repair;
	private ImageButton btn_create_or_history_rebulid;
	private TextView text_clock_or_repair, text_create_or_history_rebulid;
	private MainClockView mcv;
	private MainTitleView mtv;
	private AlphaAnimation aa;
	private String userType = "1";// 1报修，2维修 用户登录类型 TODO

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.home);
		userType = SettingLoader.getLoginUserType(this);

		initComponents();

		ListAdapter adapter = new ListAdapter(this, getData(userType));
		gridView.setAdapter(adapter);

		// 图片渐变模糊度始终
		aa = new AlphaAnimation(0.1f, 1.0f);
		// 渐变时间
		aa.setDuration(1500);
		// 展示图片渐变动画
		mcv.setAnimation(aa);
		weatherStart();
		mcv.timeStart();
		
		clearCache();
		
		updateApp();
	}

	private void updateApp() {
		UpdateApi api = new UpdateApi(this);
		api.setReturnResultListener(new ApiReturnResultListener() {
			
			@Override
			public <T> void onReturnSucceedResult(int requestCode,
					ApiResult<T> apiResult) {
				JSONObject jsonEntity = apiResult.getJsonEntity();
				//{"d":{"__type":"UpdateReturn:r","v":"2.0","u":"http:\/\/web.0427qcw.com\/update\/2.0.apk","d":"2.0新版程序，增加许多有用的功能"},"t":0}

				if(jsonEntity!=null) {
					try {
						int type = jsonEntity.getInt("t");
						switch (type) {
						case 0:// 对象
							try {
								if (jsonEntity != null) {
									if(jsonEntity.has("d")) {
										JSONObject obj = jsonEntity.getJSONObject("d");
										final VersionInfo version = new VersionInfo();
										version.parser(obj);
										
										
//										float svr = Utils.processVersion(version.getVersion());
//										float local = Utils.processVersion(Utils.getVersionName(PieWelcomeActivity.this));
										
										if(!StringUtils.isNullOrEmpty(version.getVersion())&&Float.parseFloat(version.getVersion())>Float.parseFloat(Utils.getLocalAppVersion(HomeActivity.this))) {
											final UpdateDialog tipsDialog = new UpdateDialog(HomeActivity.this,version.getVersion(),version.getDescribe())
											.setPositiveButton(new UpdateDialog.OnClickListener() {

												@Override
												public void onClick(DialogInterface dialog,
														int which) {
													dialog.dismiss();
													Intent intent = new Intent();
													intent.setAction(Intent.ACTION_VIEW);
													Uri downUrl = Uri.parse(version.getUrl());
													intent.setData(downUrl);
													try {
														startActivity(intent);
													} catch (Exception e) {
														intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
														intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
														startActivity(intent);
													}
													
												}

											})
											.setNegativeButton(new UpdateDialog.OnClickListener() {

												@Override
												public void onClick(DialogInterface dialog, int which) {
													dialog.dismiss();
												
												}
											});
											tipsDialog.setCancelable(false);
											tipsDialog.show();
										}
									}
								} 
							} catch (JSONException e) {
								e.printStackTrace();
							}
							break;
						case 1:// 数组
							break;
						case -1:// 错误
							break;

						default:
							break;
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
			
			@Override
			public <T> void onReturnLoading(int requestCode) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public <T> void onReturnFailResult(int requestCode, ApiResult<T> apiResult) {
				// TODO Auto-generated method stub
				
			}
		});
		api.update(1, this, Utils.getLocalAppVersion(this));
		
	}
	

	private void clearCache() {
		new AsyncTask<Void, Integer, Long>() {

			@Override
			protected Long doInBackground(Void... params) {
				File cache = Utils.getCachePath();
				if(cache!=null&&cache.exists()) {
					File[] files = cache.listFiles();
					for(File file : files) {
						if(file.isFile()&&file.exists()) {
							Log.e("Delete",file.getName()+ " is delete");
							file.delete();
						}
					}
				}
				return null;
			}
		}.execute();
		
	}

	@Override
	protected void onDestroy() {
		mcv.timeStop();
		super.onDestroy();
	}

	WeatherApi weatherApi;
	private GridView gridView;

	public void weatherStart() {
		final Handler cwjHandler = new Handler();
		Timer timetask = new Timer();
		weatherApi = new WeatherApi(HomeActivity.this);
		timetask.schedule(new TimerTask() {

			@Override
			public void run() {
				weatherApi
						.setReturnResultListener(new ApiReturnResultListener() {

							@Override
							public <T> void onReturnSucceedResult(
									int requestCode, ApiResult<T> apiResult) {
								Map<String, String> weatherMap = apiResult
										.getEntity();
								final String temperature = weatherMap
										.get(WeatherApi.TEMPERATURE);
								final String weather = weatherMap
										.get(WeatherApi.WEATHER);
								final String img = weatherMap
										.get(WeatherApi.IMG);

								cwjHandler.post(new Runnable() {

									@Override
									public void run() {
										mcv.setTemperature(temperature);
										mcv.setWeather(weather);
										try {
											Field field = R.drawable.class
													.getField("a" + img);
											int i = field
													.getInt(new R.drawable());
											mcv.clock_weather_icon_panel
													.startAnimation(aa);
											mcv.setWeatherIcon(i);

										} catch (Exception e) {
											Log.e("icon", e.toString());
										}
									}
								});

							}

							@Override
							public <T> void onReturnFailResult(int requestCode,
									ApiResult<T> apiResult) {

							}

							@Override
							public <T> void onReturnLoading(int requestCode) {

							}
						});
				weatherApi.getWeather(0);

			}
		}, 1000, 1000 * 60 * 60);

	}

	private void initComponents() {
		mtv = (MainTitleView) findViewById(R.id.thisTitle);
		mcv = (MainClockView) findViewById(R.id.thisClock);
		btn_dial = (ImageButton) findViewById(R.id.btn_dial);
		btn_notify = (ImageButton) findViewById(R.id.btn_notify);
		btn_center = (ImageButton) findViewById(R.id.btn_center);

		btn_clock_or_repair = (ImageButton) findViewById(R.id.btn_clock_or_repair);
		btn_create_or_history_rebulid = (ImageButton) findViewById(R.id.btn_create_or_history_rebulid);
		text_clock_or_repair = (TextView) findViewById(R.id.text_clock_or_repair);
		text_create_or_history_rebulid = (TextView) findViewById(R.id.text_create_or_history_rebulid);

		if (userType.equals(USER_TYPE_REPAIR)) {

			btn_clock_or_repair.setBackgroundResource(R.drawable.main_icon_one);
			btn_create_or_history_rebulid
					.setBackgroundResource(R.drawable.main_icon_four);
			text_clock_or_repair.setText("日志");
			text_create_or_history_rebulid.setText("交接班");

		} else if (userType.equals(USER_TYPE_SERVICE)) {
			btn_clock_or_repair.setBackgroundResource(R.drawable.paigong);
			btn_create_or_history_rebulid
					.setBackgroundResource(R.drawable.lishi);
			text_clock_or_repair.setText("派工接收");
			text_create_or_history_rebulid.setText("历史维修");
		}
		btn_dial.setOnClickListener(this);
		btn_notify.setOnClickListener(this);
		btn_center.setOnClickListener(this);
		btn_clock_or_repair.setOnClickListener(this);
		btn_create_or_history_rebulid.setOnClickListener(this);

		// 主页面的天气下面的图标
		gridView = (GridView) findViewById(R.id.gridView1);

	}

	private ArrayList<Item> getData(String type) {
		if (null == type) {
			type = USER_TYPE_REPAIR;
		}
		ArrayList<Item> list = new ArrayList<Item>();
		Item item = new Item();
		if (type.equals(USER_TYPE_REPAIR)) {

			item.item = RepairCreateActivity.class;
			item.name = "新建报修";
			item.iconId = R.drawable.repair_create;

			list.add(item);
			item = new Item();
			item.item = RepairTrackListActivity.class;
			item.iconId = R.drawable.repair_track;
			item.name = "报修跟踪";
			list.add(item);

			item = new Item();
			item.item = RepairHistoryListActivity.class;
			item.iconId = R.drawable.history_repair;
			item.name = "历史报修";
			list.add(item);
		} else {
			item = new Item();
			item.item = ServicesListActivity.class;
			item.iconId = R.drawable.repair_icon;
			item.name = "维修";
			list.add(item);
		}

		return list;
	}

	private class ListAdapter extends BaseAdapter {

		private Context context;
		private ArrayList<Item> data;
		private LayoutInflater inflater;

		public ListAdapter(Context context, ArrayList<Item> data) {
			this.context = context;
			this.data = data;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return data != null ? data.size() : 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Item item = data.get(position);
			if (item == null) {
				return null;
			}
			final ViewHolder holder;

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.home_icon_item, null);
				holder = new ViewHolder();
				holder.item = (LinearLayout) convertView
						.findViewById(R.id.home_icon);
				holder.icon = (ImageView) convertView
						.findViewById(R.id.imageView1);
				holder.name = (TextView) convertView
						.findViewById(R.id.textView1);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			updateData(holder, item);

			return convertView;
		}

		private void updateData(ViewHolder holder, final Item item) {
			holder.name.setText(item.name);
			holder.icon.setImageResource(item.iconId);

			holder.item.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, item.item);

					if (item.type != -1) {
						intent.putExtra("type", item.type);
					}
					context.startActivity(intent);
					finish();
				}
			});

		}

		final class ViewHolder {
			LinearLayout item;
			ImageView icon;
			TextView name;
		}
	}

	final class Item {
		public Class<?> item;
		public String name;
		public int iconId;
		public int type = -1;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_dial:
			gotoActivity(this, DailActivity.class);
			break;
		case R.id.btn_notify:
			gotoActivity(this, NotifykActivity.class);
			break;
		case R.id.btn_center:
			gotoActivity(this, SettingActivity.class);
			break;
		case R.id.btn_clock_or_repair:
			if (userType.equals(USER_TYPE_REPAIR)) {
				gotoActivity(this, DiaryActivity.class);
			} else if (userType.equals(USER_TYPE_SERVICE)) {
				gotoActivity(this, DispatchListActivity.class);
			}
			break;
		case R.id.btn_create_or_history_rebulid:
			if (userType.equals(USER_TYPE_REPAIR)) {
				gotoActivity(this, ShiftChangeActivity.class);
			} else if (userType.equals(USER_TYPE_SERVICE)) {
				gotoActivity(this, ServicesHistoryListActivity.class);
			}
			break;

		default:
			break;
		}

	}
	
	public static <T> void gotoActivity(Context context,Class<T> classes) {
		Intent intent = new Intent(context,classes);
		context.startActivity(intent);
	}
}
